import { Feedback } from '../models';

export default function (router) {
  /**
   * 前端接口
   * 提交意见反馈
   */
  router.post('/api/front/feedback', async ctx => {
    const { userid, type, desc, images = [] } = ctx.request.body;
    // 参数校验
    if (!userid || !type || !desc) {
      await ctx.json(false, '参数错误');
      return;
    }
    const feedback = await Feedback.create({
      user: ctx.transId(userid),
      type,
      desc,
      images,
      solved: false,
      create_time: new Date()
    });

    if (feedback) {
      await ctx.json(true, 'success');
    } else {
      await ctx.json(false, '提交反馈失败');
    }
  });

  /**
   * 后端接口
   * 获取反馈列表
   */
  router.get('/api/admin/feedback', async ctx => {
    const { name, userid, mobile, desc, sort_key: sortKey, sort_direction: sortDirection } = ctx.request.query;
    let queryParams = {};
    let userParams = {};
    if (userid) queryParams.user = ctx.transId(userid);
    if (mobile) userParams.mobile = mobile;
    if (name) userParams.username = new RegExp(name, 'i');
    if (desc) {
      const reg = new RegExp(desc.toString('utf8').trim(), 'i');
      queryParams.desc = reg;
    }
    const { page, limit } = ctx.parsePageAndLimit(ctx.request.query);

    const list = await Feedback.find(queryParams)
      .skip((page - 1) * limit)
      .limit(limit)
      .sort({ [sortKey]: sortDirection })
      .populate({
        path: 'user',
        select: 'username avatar mobile',
        match: userParams
      });
    const total = await Feedback.countDocuments(queryParams);
    await ctx.json(true, '获取反馈成功', { list, total });
  });

  /**
   * 后端接口
   * 标记反馈已解决
   */
  router.put('/api/admin/feedback/:id', async ctx => {
    const id = ctx.params.id;
    const result = await Feedback.updateOne({ _id: id }, { $set: ctx.request.body });
    if (result.ok === 1) {
      const newest = await Feedback.findById(id);
      await ctx.json(true, '更新反馈成功', newest);
    } else {
      await ctx.json(false, '更新反馈失败', result);
    }
  });

  /**
   * 后端接口
   * 删除反馈
   */
  router.delete('/api/admin/feedback/:id', async ctx => {
    const id = ctx.params.id;
    const operation = await Feedback.deleteOne({ _id: id });
    if (operation.ok) {
      await ctx.json(true, '删除反馈成功');
    } else {
      await ctx.json(false, '删除反馈失败');
    }
  });
}
